package com.qifei.xmlg_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qifei.xmlg_backend.DTO.logs.LogsQueryDTO;
import com.qifei.xmlg_backend.entity.Logs;
import com.qifei.xmlg_backend.entity.PageBean;
import com.qifei.xmlg_backend.mapper.LogsMapper;
import com.qifei.xmlg_backend.service.ILogsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 操作日志表 服务实现类
 * </p>
 *
 * @author logs
 * @since 2025-06-17
 */
@Service
public class LogsServiceImpl extends ServiceImpl<LogsMapper, Logs> implements ILogsService {
    @Override
    public void recordLog(Long userId, String username, String operation, String method, String url, String ip, Integer status) {
        Logs log = new Logs();
        log.setUserId(userId);
        log.setUsername(username);
        log.setOperation(operation);
        log.setMethod(method);
        log.setUrl(url);
        log.setIp(ip);
        log.setStatus(status);
        log.setCreateTime(LocalDateTime.now());
        this.save(log);
    }

    @Override
    public IPage<Logs> getLogsPage(LogsQueryDTO queryDTO,Integer page,Integer pageSize) {
        LambdaQueryWrapper<Logs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(queryDTO.getUsername() != null && !queryDTO.getUsername().isEmpty(),
                Logs::getUsername, queryDTO.getUsername());
        queryWrapper.like(queryDTO.getMethod() != null && !queryDTO.getMethod().isEmpty(),
                Logs::getMethod, queryDTO.getMethod());
        queryWrapper.like(queryDTO.getUrl() != null && !queryDTO.getUrl().isEmpty(),
                Logs::getUrl, queryDTO.getUrl());
        queryWrapper.like(queryDTO.getIp() != null && !queryDTO.getIp().isEmpty(),
                Logs::getIp, queryDTO.getIp());
        queryWrapper.orderByDesc(Logs::getCreateTime);

        Page<Logs> pageObj = new Page<>(page, pageSize);
        return this.page(pageObj, queryWrapper);
    }
}
